<?php

class Dao_BaseModel extends DB_Base {

    private $_redisTool;

    public function __construct ()
    {
        $this->_redisTool = RedisTool::getInstance ();
        parent::__construct ();
    }

    /*
     * 获取项目的redis缓存前缀
     */

    private function getRedisPerfix ()
    {
        $_config = Yaf_Registry::get ( 'config' )->database->redis->toArray ();
        $prefix  = $_config[ 'prefix' ];
        return $prefix;
    }

    /**
     * 获得cache key.
     * @param int $id
     * @return string
     */
    public function getCacheKey ($keyword)
    {
        $perfix = $this->getRedisPerfix ();
        return $perfix . $keyword;
    }

    /**
     * 通过取信息缓存.
     * @param string $key
     * @return bool|mixed
     */
    public function getCacheByKey ($key)
    {
        $t = $this->_redisTool->get ( $key );
        $t = $t ? json_decode ( $t , true ) : false;
        return $t;
    }

    /**
     * 设置信息缓存.
     * @param string $key 键
     * @param array $info  值
     * @param int $extime 缓存时间
     * @return mixed
     */
    public function setCache ($key , $info , $extime)
    {
        return $this->_redisTool->set ( $key , json_encode ( $info ) , $extime );
    }

    /**
     * 删除信息缓存.
     * @param strint $key
     * @return mixed
     */
    public function deleteCacheByKey ($key)
    {
        return $this->_redisTool->delete ( $key );
    }
    
    /**
     * 从缓存中取信息.
     * @param array $ids
     * @return array
     */
    public function getFromCache(Array $ids,$key)
    {/*{{{*/
        if(empty($ids)) return array();
        $keys = array_map(function($id) use($key) {
            return $key . $id;
        }, array_unique($ids));
        $infos = $this->_redisTool->mget($keys);
        if ($infos)
        {
            foreach ($infos as &$info){
                if (!$info || in_array($info, array("null", "NULL")))continue;
                $info= json_decode($info, true);
                $ret[$info['id']] = $info;
            }
        }
        return isset($ret) ? $ret : array();
    }/*}}}*/

}
